package org.feng.start.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.feng.datasource.DynamicDataSourceContextHolder;
import org.feng.datasource.annotation.ChangeDataSource;
import org.feng.start.entity.Student;
import org.feng.start.service.IStudentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 学生控制器-测试切换数据源
 *
 * @author feng
 */
@Slf4j
@RequestMapping("/student")
@RestController
public class StudentController {

    @Resource
    private IStudentService studentService;

    @GetMapping("/list/{merchant}")
    public List<Student> list(@PathVariable String merchant) {
        try {
            // 切换数据源
            DynamicDataSourceContextHolder.setDataSourceKey(merchant);

            // 查库
            List<Student> resultList = studentService.list();

            log.info("查询结果：{}", resultList);

            return resultList;
        } finally {
            // 清除当前数据源
            DynamicDataSourceContextHolder.removeDataSourceKey();
        }
    }


    @GetMapping("/listStu/master")
    public List<Student> listStu() {
        // 查库
        List<Student> resultList = studentService.list();

        log.info("查询结果：{}", resultList);

        return resultList;
    }

    @ChangeDataSource(merchant = "slave1")
    @GetMapping("/listStu/slave1")
    public List<Student> listStu1() {
        // 查库
        List<Student> resultList = studentService.list();

        log.info("查询结果：{}", resultList);

        return resultList;
    }

    @ChangeDataSource(merchant = "slave2")
    @GetMapping("/listStu/slave2")
    public List<Student> listStu2() {
        // 查库
        List<Student> resultList = studentService.list();

        log.info("查询结果：{}", resultList);

        return resultList;
    }
}
